var api = require('../../utils/api');
var utils = require('../../utils/utils');

Page({
    data: {
        pair: [], // 交易对，如['btc', 'usdt']
        symbols: [], // 原始api接口取到的所有币对，包括下单价与量的最小小数点位数
        formatSymbols: [], // 经过格式的交易对，方便在Picker上显示
        balanceData: [], // 原始api接口取到用户余额，包括btc、eth、usdt各种币详情
        balance: '', // 当前币种的余额，用于页面上渲染
        index: 0, // 当前picker的index，用到控制显示picker与余额等诸多渲染 
        orders: [], // 当前条件订单列表
        side: 'buy', // 当前买卖方向
        sides: [{
                value: 'buy',
                title: '买入',
                color: 'green',
                bgColor: 'bc_green',
                checked: 'true'
            },
            {
                value: 'sell',
                title: '卖出',
                color: 'red',
                bgColor: 'bc_red',
            },
        ],
        mode: 'normal',
        modes: [{
                name: 'normal',
                value: '普通',
                checked: 'true'
            },
            {
                name: 'robot',
                value: '抢单',
            },
        ],
        robotInterval: '', // 抢单定时器
        price: '', // 委托价
        amount: '2500', // 委托数量
        cost: 0, // 成本价
    },
    onLoad: function () {
        this.loadSymbols();
    },
    loadOrders: function () {
        // console.log(this.data.pair);
        api.getOrders({
            symbol: this.data.pair.join(''),
            states: 'submitted,partial_filled',
        }).then(orders => {
            this.setData({
                orders: utils.formatOrders(orders)
            });
            // console.log('订单');
            // console.log(utils.formatOrders(orders));
        });
    },
    loadSymbols: function () {
        // api-加载所有币对
        api.symbols().then(symbols => {
            var newSymbols = utils.generateSymbols();
            symbols = newSymbols.concat(symbols);
            // console.log(symbols);
            var formatSymbols = this.data.formatSymbols;
            symbols.forEach(item => {
                formatSymbols.push(item.base_currency.toUpperCase() + '/' + item.quote_currency.toUpperCase());
            });
            this.setData({
                symbols: symbols,
                formatSymbols: formatSymbols,
            });
            return symbols;
        }).then(symbols => {
            // 设定默认币对，以及生成pair数组以供渲染
            utils.findDefaultCurrency(symbols).then(index => {
                var pair = [symbols[index].base_currency, symbols[index].quote_currency];
                // console.log(index);
                this.setData({
                    index: index,
                    pair: pair,
                });
            });
            return symbols;
        }).then(() => {
            // api-获取当前币种余额
            var index = this.data.index;
            api.getUserInfo().then(balanceData => {
                // console.log(balanceData);
                this.setData({
                    balanceData: balanceData
                });
                // 以指定的下标获取相应值
                this.findBalanceByCurrency();
            });
            // api 获取交易深度
            this.loadDepth();
        }).then(() => {
            // api-获取当前币对订单列表
            var interval = setInterval(() => {
                this.loadDepth();
                this.loadOrders();
            }, 1000);
            // 保存interval方便需要的时候取消定时
            this.setData({
                interval: interval
            });
            // 关闭下拉刷新动画
            wx.stopPullDownRefresh();
        });
    },
    loadDepth: function () {
        api.depth(this.data.pair.join('')).then(res => {
            this.setData({
                depthData: utils.formatDepth(res),
            });
        });
    },
    bindPickerChange: function (e) {
        var index = e.detail.value;
        var symbols = this.data.symbols;
        this.setData({
            index: index,
            pair: [symbols[index].base_currency, symbols[index].quote_currency],
        })
        // 获取当前币种余额
        this.findBalanceByCurrency();
        // 获取当前币对订单列表
        this.loadOrders();
        // 获取交易深度
        // this.loadDepth();
    },
    order: function (e) {
        // 下单方法
        var form = e.detail.value;
        var param = {
            // price: 0.01,
            // amount: 3,
            type: 'limit',
            price: form.price,
            amount: form.amount,
            side: this.data.side, // 买入默认，Todo，改为segmentControl来实现,
            symbol: this.data.pair.join(''),
        };
        // console.log(param);
        var order = () => {
            api.order(param).then(order => {
                // console.log(order);
                wx.showToast({
                    title: '下单成功'
                });
                this.loadOrders();
            });
        }
        if (this.data.mode == 'robot') {
            var robotInterval = setInterval(() => {
                order();
            }, 5000);
            this.setData({
                robotInterval: robotInterval
            });
        } else {
            order();
        }
    },
    cancel: function (e) {
        var index = e.currentTarget.dataset.index;
        var order_id = this.data.orders[index].id;
        api.cancelOrder(order_id).then(res => {
            wx.showToast({
                title: '撤单成功'
            });
            this.loadOrders();
        });
    },
    findBalanceByCurrency: function () {
        // 查询相应币对的余额
        var symbols = this.data.symbols;
        var index = this.data.index;
        var quote_currency = symbols[index].quote_currency;
        var base_currency = symbols[index].base_currency;
        // "base_currency":"ft","quote_currency":"usdt"
        var quote_balace = Number(utils.findBalanceByCurrency(this.data.balanceData, quote_currency));
        var base_balace = Number(utils.findBalanceByCurrency(this.data.balanceData, base_currency));
        var balance = this.data.side == 'buy' ? quote_balace : base_balace;
        // 计算成本价
        var principal = wx.getStorageSync('principal');
        var cost = (principal - quote_balace) / base_balace;
        cost = cost.toFixed(4);
        // 计算盈亏点
        api.depth(this.data.pair.join('')).then(res => {
            var depthData = utils.formatDepth(res);
            var dollor = 6.6;
            var price = depthData.bids[0];
            // 可买或可卖
            var trade_limit = this.data.side == 'buy' ? balance / price : balance * price;
            // 市值
            var value = (price * base_balace);
            var valueCny = (value * dollor).toFixed();
            // 盈亏
            var earn = (value + quote_balace - principal).toFixed(0);
            // 折合人民币
            var earnCny = (earn * dollor).toFixed();
            // 盈率
            var ratio = (100 * (price / cost - 1)).toFixed(2) + '%';
            // 仓位
            var level = ((principal - balance) / principal * 10).toFixed(1);
            // 持仓
            var spend = principal - balance;
            // 持仓人民币
            var spendCny = spend * dollor;
            this.setData({
                ratio: ratio, // 盈亏几个点
                valueCny: valueCny, // 人民币市值
                value: value.toFixed(), // USDT市值
                earn: earn, // 盈亏多少USDT
                earnCny: earnCny, // 盈亏多少人民币
                level: level, // 仓位
                spend: spend.toFixed(), // 持仓
                spendCny: spendCny.toFixed(), // 持仓人民币
                trade_limit: trade_limit.toFixed(), // 可买或可卖
            });
        });
        this.setData({
            balance: balance,
            cost: cost,
        });

    },
    onShow: function () {
        if (!wx.getStorageSync('key') || !wx.getStorageSync('secret')) {
            wx.showModal({
                title: '请配置key与secret',
                showCancel: false,
                success: res => {
                    this.showConfig()
                }
            })
        }
    },
    onPullDownRefresh: function () {
        // 下拉刷新
        this.loadSymbols();
    },
    sideChange: function (e) {
        // 买卖方向切换
        this.setData({
            side: e.detail.value
        });
        this.findBalanceByCurrency();
    },
    getPrice: function (e) {
        var {
            price,
            side
        } = e.currentTarget.dataset;
        this.setData({
            price: utils.cutFixed(price, 3),
            sides: this.data.sides.map(item => {
                if (side == item.value) {
                    item.checked = true;
                } else {
                    item.checked = false;
                }
                return item;
            }),
            side: side,
        });
        this.total();
    },
    modeChange: function (e) {
        var mode = e.detail.value;
        // 模式切换
        this.setData({
            mode: mode
        });
    },
    cancelAll: function () {
        this.data.orders.forEach(order => {
            var order_id = order.id;
            api.cancelOrder(order_id).then(res => {
                wx.showToast({
                    title: '撤单成功'
                });
                this.loadOrders();
            });
        });
    },
    stopRobot: function () {
        // 终止自动抢单
        clearInterval(this.data.robotInterval);
        wx.showToast({
            title: '成功终止'
        });
    },
    priceChange: function (e) {
        // 输入框取值
        this.setData({
            price: e.detail.value,
        });
        this.total();
    },
    amountChange: function (e) {
        // 输入框取值
        this.setData({
            amount: e.detail.value,
        });
        this.total();
    },
    total: function () {
        // 金额汇总
        this.setData({
            total: utils.cutFixed(this.data.price * this.data.amount, 2)
        });
    },
    showMore: function () {
        wx.showActionSheet({
            itemList: ['查看余额', '设置密钥'],
            success: (res) => {
                switch (res.tapIndex) {
                    case 0:
                        this.showBalance();
                        break;
                    case 1:
                        this.showConfig();
                        break;
                    default:
                        break;
                }
            },
            fail: function (res) {
                console.log(res.errMsg)
            }
        })
    },
    showBalance: function () {
        wx.navigateTo({
            url: '../../member/balance/balance'
        });
    },
    showConfig: function () {
        wx.navigateTo({
            url: '../../member/config/config'
        });
    },
    showDetail: function () {
        var content = `市值:${this.data.value}(￥${this.data.valueCny})\r\n`;
        content += `成本价: ${this.data.cost}\r\n`;
        content += `持仓: ${this.data.spend}(￥${this.data.spendCny})\r\n`;
        content += `仓位: ${this.data.level}\r\n`;
        content += `盈率: ${this.data.ratio}\r\n`;
        content += `盈利: ${this.data.earn}(￥${this.data.earnCny})`;
        wx.showModal({
            title: '本次盈亏',
            content: content,
            showCancel: false,
        });
    },
    showOrders: function () {
        var symbol = this.data.pair.join('');
        wx.navigateTo({
            url: `../../trade/orders/orders?symbol=${symbol}`
        });
    },
    showKLine: function () {
        var symbol = this.data.pair.join('');
        wx.navigateTo({
            url: `../../trade/kline/kline?symbol=${symbol}`
        });
    },
})